package com.ruxiaoxin.share.controller.admin;

import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ruxiaoxin.share.domain.user.User;
import com.ruxiaoxin.share.service.user.UserService;
import com.ruxiaoxin.share.util.MD5Utils;
import com.ruxiaoxin.share.controller.CaptchaController;

/**
 * 
 * @author ruxiaoxin
 *
 */
@Controller
public class UserController {
	@Autowired
	UserService userService;
	@RequestMapping(value = "/register", method = GET)
	 public String index(Model model) {
		return "register";
	}
	@RequestMapping(value = "/register", method = POST)
	public String register(Model model,HttpServletRequest request, HttpSession session) {
		User registerUser = new User();
		String email = request.getParameter("form_email");	//邮箱
		String password = request.getParameter("form_password");//密码
		String userName = request.getParameter("form_name");
		try {
			checkCaptcha(request, session);
			if(null != email && !"".equals(email) && null != password && !"".equals(password) &&
					 null != userName && !"".equals(userName)){
				if(null != userService.getByEmail(email)){
					return "redirect:/register?code=3&email="+email;
				}
				registerUser.setEmail(email).setPassword(MD5Utils.MD5Encode(password)).setUserName(userName).setRegisterTime(System.currentTimeMillis()).setIsValue(1);
				userService.save(registerUser);
				model.addAttribute("message", "注册成功").addAttribute("user", registerUser);
				return "register-message";	
			}else{
				return "redirect:/register?code=1&email="+email;
			}
		}catch(Exception e){
			return "redirect:/register?code=2&email="+email;
		}
	}
	/**
	 * 登录
	 * @param request
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request,Model model) {
		return "/login";
	}
	
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String login(HttpServletRequest request, HttpSession session) {
		
		
		Subject subject = SecurityUtils.getSubject();
		if (subject.isAuthenticated()) {
			subject.logout();
		}
		try {
			//产生令牌
			AuthenticationToken token = createToken(request);
			//验证码
			checkCaptcha(request, session);
			//验证令牌
			subject.login(token);
			//把当前user放在session中,同时返回user
			User user= addUserToSession(subject);
			return "redirect:/people/"+user.getId();
		} catch (Exception e) {
			return "redirect:/login?code=" + translateException(e);
		}
		
	}
	
	@RequestMapping(value = "/people/{id}", method = RequestMethod.GET)
	public String people(@PathVariable("id") String id, Model model) {
		Subject subject = SecurityUtils.getSubject();
		User currentUser = (User) subject.getSession().getAttribute("user");
		if(null != currentUser){
			//登陆用户
			model.addAttribute("isLogin", true);
		 	if(currentUser.getId().equals(id)){
		 		//本人登录自己的主页
		 		model.addAttribute("isMe", true);
		 	}else{
		 		//登录用户访问别人的主页
		 		model.addAttribute("isMe", false);
		 	}
		 	model.addAttribute("currentUser", currentUser);
		}else{
			//非登录用户访问别人的主页
			model.addAttribute("isLogin", false);
			model.addAttribute("isMe", false);		
		}
		model.addAttribute("user", userService.get(id));
		return "user";
	}
	@RequestMapping(value="/logout")
	public String logout(@RequestParam(value="fromId",required = false) String fromId){
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		if(null != fromId && "".equals(fromId))
			return "redirect:/people/"+fromId;
		else
			return "redirect:/login";
	}
	
	@RequestMapping(value="/accounts",method = RequestMethod.GET)
	public String account(Model model){
		Subject subject = SecurityUtils.getSubject();
		User user = (User) subject.getSession().getAttribute("user");
		if(null != user){
			model.addAttribute("user", user);
			return "account";
		}else
			return "redirect:/login";
	}
	/**
	 * 修改密码
	 * @param model
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/accounts/changepwd",method = RequestMethod.POST)
	public String accountEdit(Model model,
			@RequestParam(value="old",required = false) String oldpassword,
			@RequestParam(value="new",required = false) String newpassword){
		Subject subject = SecurityUtils.getSubject();
		User currrentUser = (User) subject.getSession().getAttribute("user");
		if(null != currrentUser){
			if(null != oldpassword){
				if(MD5Utils.MD5Encode(oldpassword).equals(currrentUser.getPassword())){
					try {
						currrentUser.setPassword(MD5Utils.MD5Encode(newpassword));
						userService.update(currrentUser);
						return "success";
					}catch(Exception e){
						return "error";
					}
				}else{
					return "fail";
				}
			}else{
				return "error";
			}			
		}else
			return "error";
	}
	/**
	 * 检查验证码
	 * @param request
	 * @param session
	 */
	public void checkCaptcha(HttpServletRequest request,HttpSession session){
		String captcha = WebUtils.getCleanParam(request, "captcha");
		CaptchaController.checkCaptcha(captcha, session);
	}

	private AuthenticationToken createToken(HttpServletRequest request) {
		String email = WebUtils.getCleanParam(request, "form_email");
		String password = WebUtils.getCleanParam(request, "form_password");
		
		String passwordAsMd5 = MD5Utils.MD5Encode(password);
		String rememberMeAsString = WebUtils.getCleanParam(request, "remember");
		boolean rememberMe = false;
		if (null != rememberMeAsString) {
			rememberMe = Boolean.valueOf(rememberMeAsString);
		}
		String host = request.getRemoteHost();
		return new UsernamePasswordToken(email, passwordAsMd5, rememberMe, host);
	}
	public User addUserToSession(Subject subject){
		String email = (String) subject.getPrincipal();
		User user = userService.getByEmail(email);
		subject.getSession().setAttribute("user", user);
		return user;
	}
	
	private int translateException(Exception e) {
		//账号错误
		if (e instanceof UnknownAccountException) {
			return 1;
		}
		//账号异常
		if (e instanceof LockedAccountException) {
			return 2;
		}
		//验证错误
		if (e instanceof AuthenticationException) {
			return 3;
		}
		return 4;
	}
	
}
